package com.apes.bi.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.bi.repository.AppletRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
class AppletConnectStore extends DomainService {
    @Autowired
    AppletRepository appletRepository;

    static List<AppletConnect> appletConcents = new ArrayList<>();


    static void add(WebSocketServer wss, JSONObject message){
        AppletConnect appletConnent = new AppletConnect(message.getString("appletId"), message.getString("postId"), wss);
        appletConcents.add(appletConnent);
    }

    static void remove(WebSocketServer wss, JSONObject message){
        AppletConnect appletConnent= appletConcents.stream()
                .filter(item -> item.getAppletId().equals(message.getString("appletId")) && item.getWss() == wss && message.getString("postId").equals(item.getPostId()) ).findFirst().get();
        appletConcents.remove(appletConnent);
    }

    /***
     * 移除连接被关闭的监听项目
     * @param wss
     */
    static void onClose(WebSocketServer wss){
        appletConcents = appletConcents.stream().filter( item -> item.getWss() != wss).collect(Collectors.toList());
    }

    public Map<String,List<AppletConnect>> getGroupAppletConnent(){
        return appletConcents.stream().collect(Collectors.groupingBy(AppletConnect::getAppletId));
    }

    static class AppletConnect {
        private WebSocketServer wss;
        private String appletId;
        private String postId;

        AppletConnect(String appletId, String postId, WebSocketServer wss){
            this.wss = wss;
            this.appletId = appletId;
            this.postId = postId;
        }

        public String getAppletId() {
            return appletId;
        }

        public WebSocketServer getWss() {
            return wss;
        }
        public String getPostId(){return postId;}
        public String getUserId(){return wss.getUserId();}

    }

}